﻿namespace LS.Nc6.Web.Entry.Areas.Systems.Controllers
{
    [Route("[area]/[controller]/[action]")]
    [Area("Systems")]
    [ApiDescriptionSettings("Default")]
    public class DictionaryController : BaseAdminController
    {
        #region 字典管理
        private readonly ISysDictionaryService _dictionaryService;
        private readonly ICache _cache;
        public DictionaryController(ISysDictionaryService dictionaryService, IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            : base(cacheOptions, resolveNamed)
        {
            _dictionaryService = dictionaryService;

            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;

        }
        #endregion

        #region 页面
        public ActionResult Index()
        {
            SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            return View();
        }
       
        public ActionResult CreatDictionaryType()
        {
            SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            var model = new SysDictionaryEntity();
            model.Isenable = true;
            return View("EditDictionaryType", model);
        }
        public async Task<ActionResult> EditDictionaryType(long id)
        {
            SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model =await _dictionaryService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            return View(model);
        }

        public ActionResult CreatDictionary()
        {
            SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            var model = new SysDictionaryEntity();
            model.ParentId  = string.IsNullOrEmpty(Request.Query["pid"]) ? 0: Request.Query["pid"].ToString().ParseToLong();
            model.Isenable = true;
            
            return View("EidtDictionary", model);
        }
        public async Task<ActionResult> EidtDictionary(long id,string pcode)
        {
            SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model =await _dictionaryService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            return View(model);
        }
        #endregion

        #region 公共方法
        [HttpGet]
        public async Task<ResponseResultDataList> GetDictionary()
        {
            string keyword = RequestHelper.FilterParam(Request.Query["dicname"]);
            string dcode= RequestHelper.FilterParam(Request.Query["dcode"]);
            string pid = RequestHelper.FilterParam(Request.Query["pid"]);

            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];

            var expable = Expressionable.Create<SysDictionaryEntity>();

            expable.AndIF(!string.IsNullOrEmpty(keyword), a => a.Dname.Contains(keyword));
            expable.AndIF(!string.IsNullOrEmpty(dcode), a => a.Dvalue.Contains(dcode));
            expable.AndIF(!string.IsNullOrEmpty(pid), a => a.ParentId == pid.ParseToLong() );
            var exp = expable.ToExpression();

            
            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<SysDictionaryEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = (a) => new { a.Id };
            }
            else
            {
                //实现字段排序
                expressionOrder = (a) => new { a.CreateDate };
            }
            var result = await  _dictionaryService.PageList(exp, page,limit, expressionOrder);
            
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Items, count = result.TotalCount };
        }

        
        /// <summary>
        /// 字典类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResultDataList> GetDictionaryType()
        {
            string keyword = RequestHelper.FilterParam(Request.Query["typeName"]);
            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];

            var expable = Expressionable.Create<SysDictionaryEntity>();

            expable.And(a=> SqlFunc.IsNull(a.ParentId,0)==0);
            expable.AndIF(!string.IsNullOrEmpty(keyword), a => a.Dname.Contains(keyword));
            var exp = expable.ToExpression();
            var filed = RequestHelper.FilterParam(field);
            var filedOrder = RequestHelper.FilterParam(order);

            Expression<Func<SysDictionaryEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(filed) || string.IsNullOrEmpty(filedOrder))
            {
                expressionOrder = (a) => new { a.Id };
            }
            else
            {
                //实现字段排序
                expressionOrder = (a) => new { a.CreateDate };
            }

            var result = await _dictionaryService.PageList(exp, page, limit, expressionOrder);

            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Items, count = result.TotalCount };
          
        }
        /// <summary>
        /// 保存字典
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveDictionary([FromBody]SysDictionaryEntity model)
        {
            bool power = true;
            long result = 0;
            if (model.Id > 0)
            {
                power = SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel =await _dictionaryService.GetByIdAsync(model.Id);
                CommonMethodHelper.MapperToModel(editmodel, model, null);
                result = await _dictionaryService.UpdateAsync(editmodel);
            }
            else
            {
                power = SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                result = await _dictionaryService.InsertAsync(model);
            }
           return  ResponseHelper.SaveResult(result);

        }

        /// <summary>
        /// 保存字典类型
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveDictionaryType([FromBody] SysDictionaryEntity model)
        {
            bool power = true;
            long result = 0;
            if (model.Id > 0)
            {
                power = SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel = await _dictionaryService.GetByIdAsync(model.Id);
                if (editmodel == null || editmodel.IsDeleted == 1)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.NONEXISTENT);
                }
                CommonMethodHelper.MapperToModel(editmodel, model, null);
                result = await _dictionaryService.UpdateAsync(editmodel);
            }
            else
            {
                power = SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                result = await _dictionaryService.InsertAsync(model);
            }
            return ResponseHelper.SaveResult(result);
        }
        /// <summary>
        ///删除字典
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
       public async Task<ResponseResult> DelDict([FromBody]DeletDataInput input)
        {
            var r=SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(),false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WSCQX);
            }
            int result = await _dictionaryService.DeleteAsync(input.Ids);
            return ResponseHelper.DeleteResult(result);
        }
        /// <summary>
        /// 删除字典类型
        /// </summary>
        /// <param name="dcode"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> DelDictType([FromBody] DeletDataInput input)
        {
            var r = SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WSCQX);
            }
            if(string.IsNullOrEmpty(input.Ids))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            
            int result = await _dictionaryService.DeleteType(input.Ids);

           return  ResponseHelper.DeleteResult(result);
        }
        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> ModifyState(MoifyStateInput input)
        {
            var r = SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WXGQX);
            }
            if (string.IsNullOrEmpty(input.Id.ToString()))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            int result =await _dictionaryService.ModifyState(input.Id,input.State);

            return ResponseHelper.OperateResult(result);

           
        }
        #endregion

        #region 私有方法

        #endregion

    }
}